package com.cym.service;

import org.noear.solon.annotation.Inject;
import org.noear.solon.aspect.annotation.Service;

import com.cym.model.Function;
import com.cym.model.Project;
import com.cym.model.ProjectUser;
import com.cym.sqlhelper.bean.Page;
import com.cym.sqlhelper.utils.ConditionAndWrapper;
import com.cym.sqlhelper.utils.ConditionOrWrapper;
import com.cym.sqlhelper.utils.SqlHelper;

import cn.hutool.core.util.StrUtil;

@Service
public class ProjectService {
	@Inject
	SqlHelper sqlHelper;

	public Page<Project> search(Page pageReq, String keywords) {
		ConditionAndWrapper conditionAndWrapper = new ConditionAndWrapper();

		if (StrUtil.isNotEmpty(keywords)) {
			conditionAndWrapper.and(new ConditionOrWrapper().like("name", keywords));
		}

		Page<Project> pageResp = sqlHelper.findPage(conditionAndWrapper, pageReq, Project.class);

		return pageResp;
	}

	public Project getByName(String name, String projectId) {
		ConditionAndWrapper conditionAndWrapper = new ConditionAndWrapper().eq(Project::getName, name);
		if(StrUtil.isNotEmpty(projectId)) {
			conditionAndWrapper.ne(Project::getId, projectId);
		}
		
		return sqlHelper.findOneByQuery(conditionAndWrapper, Project.class);
	}

	public boolean hasProjectFunction(String id) {
		return sqlHelper.findCountByQuery(new ConditionAndWrapper().eq(Function::getProjectId, id), Function.class) > 0;
	}

	public void deleteById(String id) {
		sqlHelper.deleteById(id, Project.class);
		sqlHelper.deleteByQuery(new ConditionAndWrapper().eq(ProjectUser::getProjectId, id), ProjectUser.class);
	}

	public void insertOrUpdate(Project project, String[] userIds) {
		sqlHelper.insertOrUpdate(project);
		
		sqlHelper.deleteByQuery(new ConditionAndWrapper().eq(ProjectUser::getProjectId, project.getId()), ProjectUser.class);
		
		for(String userId:userIds) {
			ProjectUser projectUser = new ProjectUser();
			projectUser.setProjectId(project.getId());
			projectUser.setUserId(userId);
			sqlHelper.insertOrUpdate(projectUser);
		}
		
	}

//	public List<User> getUserList(String projectId) {
//		List<String> userIds =  sqlHelper.findPropertiesByQuery(new  ConditionAndWrapper().eq(ProjectUser::getProjectId, projectId), ProjectUser.class, ProjectUser::getUserId);
//	
//		return sqlHelper.findListByIds(userIds, User.class);
//	}
}
